package com.cjy.common.utils;

import com.base.common.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * 应用程序工具类 2013-12-6 下午4:29:20
 * 
 * @author jay.zhoujingjie
 */
public class ApplicationUtils {
	private static Log LOG = LogFactory.getLog(ApplicationUtils.class);

	/**
	 * 获取远程IP地址
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 远程IP地址
	 * @author jay.zhoujingjie
	 */
	public final static String getRemoteAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		String unknown = " unknown ";
		if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取远程mac地址
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 远程mac地址
	 * @author jay.zhoujingjie
	 */
	public static String getRemoteMacAddress(HttpServletRequest request) {
		return getRemoteMacAddress(getRemoteAddress(request));
	}

	/**
	 * 获取远程Mac地址
	 * 
	 * @return 远程Mac地址
	 * @author jay.zhoujingjie
	 */
	public static String getRemoteMacAddress(String ip) {
		String mac = "0";
		try {
			LineNumberReader lineNumberReader = new LineNumberReader(
					new InputStreamReader(Runtime.getRuntime()
							.exec("nbtstat -A " + ip).getInputStream()));
			String line = null;
			while ((line = lineNumberReader.readLine()) != null) {
				if (line.toUpperCase().contains("MAC")) {
					mac = line.substring(line.length() - 17);
				}
			}
		} catch (IOException e) {
			LOG.error(e.getMessage());
		}
		return mac;
	}

	/**
	 * 判断当前操作是否有权限
	 * 
	 * @param authId
	 * @return 是否包含权限
	 * @author jay.zhoujingjie
	 */
	public static boolean isAllowAsThisAction(String authId) {

		// List<String> authorities = (List)
		// ActionContext.getContext().getSession().get(GlobaConstants.LOGIN_USER_AUTHORITY);
		// return (!StringUtils.isEmptyByTrim(authId)) &&
		// authorities.contains(authId);
		return true;
	}

	/**
	 * 判断是否是异步(ajax)请求
	 * 
	 * @param request
	 * @return boolean
	 * @author jay.zhoujingjie
	 */
	public static boolean isAsyncRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		return header != null && "XMLHttpRequest".equals(header);
	}

}
